package com.tianji.remark.service.impl;

import com.tianji.common.utils.ObjectUtils;
import com.tianji.common.utils.UserContext;
import com.tianji.remark.domain.dto.LikeRecordFormDTO;
import com.tianji.remark.domain.po.LikedRecord;
import com.tianji.remark.mapper.LikedRecordMapper;
import com.tianji.remark.service.ILikedRecordService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.connection.StringRedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

//无敌了

/**
 * <p>
 * 点赞记录表 服务实现类
 * </p>
 *
 * @author author
 * @since 2024-11-15
 */
@Service
@RequiredArgsConstructor
public class LikedRecordServiceImpl extends ServiceImpl<LikedRecordMapper, LikedRecord> implements ILikedRecordService {
    private final StringRedisTemplate redisTemplate;


    //"点赞或取消点赞"
    @Override
    public void liked(LikeRecordFormDTO likeRecordFormDTO) {
        //判断新增还是删除
        Boolean flag = likeRecordFormDTO.getLiked()==true?addlike(likeRecordFormDTO):deleteLike(likeRecordFormDTO);

        //判断返回值
        if (!flag) {
            //点赞失败结束
            return;
        }
        //方案二
        //点赞成功缓存++
//        Double scoreResult = likeRecordFormDTO.getLiked() ? incrmentZset(likeRecordFormDTO, 1) : incrmentZset(likeRecordFormDTO, -1);
        //方案一
        Long likeTimes = redisTemplate.opsForSet().size(LIKE_BIZ_KEY_PREFIX + likeRecordFormDTO.getBizId());
        if(ObjectUtils.isEmpty(likeTimes)){
            return;
        }

        // 4、缓存点赞总数到redis zset结构中
        redisTemplate.opsForZSet().add(
                LIKE_TIMES_KEY_PREFIX + likeRecordFormDTO.getBizType(),
                likeRecordFormDTO.getBizId().toString(),
                likeTimes
        );

    }

    @Override
    public Set<Long> isBizLiked(List<Long> bizIds) {
        // 1、获取当前登录人
        Long userId = UserContext.getUser();

        // 2、循环查询点赞状态，将已点赞的业务ID放入集合
        Set<Long> ids = new HashSet<>(bizIds.size());

        // 方式一：循环调用isMember实现，效率较低
        /*for (Long bizId : bizIds) {
            // 3、判断当前用户是否点过赞，如果是，放入集合中
            Boolean exists = redisTemplate.opsForSet().isMember(LIKE_BIZ_KEY_PREFIX + bizId, userId.toString());
            if(exists){
                ids.add(bizId);
            }
        }*/

        // 方式二：通过pipeline管道技术实现   // 【true,false,false,true】
        List<Object> pipelineResultList = redisTemplate.executePipelined((RedisCallback<Object>) connection -> {
            StringRedisConnection connect = (StringRedisConnection) connection;
            for (Long bizId : bizIds) {
                connect.sIsMember(LIKE_BIZ_KEY_PREFIX + bizId, userId.toString());
            }
            return null;
        });

        // 3、提取点赞过的业务ID并返回
        // 方式一：通过for循环逐个取
        /*for (int i = 0; i < pipelineResultList.size(); i++) {
            Boolean flag = (Boolean)pipelineResultList.get(i);
            if(flag){
                Long bizId = bizIds.get(i);
                ids.add(bizId);
            }
        }*/

        // 方式二：通过stream流
        return IntStream.range(0,pipelineResultList.size())
                .filter(i -> (Boolean) pipelineResultList.get(i))
                .mapToObj(bizIds::get)
                .collect(Collectors.toSet());
    }

    //方案二
    private Double incrmentZset(LikeRecordFormDTO likeRecordFormDTO, int i) {
        Double v = redisTemplate.opsForZSet().incrementScore(likeRecordFormDTO.getBizId().toString(), UserContext.getUser().toString(), i);
        return v;
    }

    //删除点赞记录
    private Boolean deleteLike(LikeRecordFormDTO likeRecordFormDTO) {
        Long result =redisTemplate.opsForSet().remove(likeRecordFormDTO.getBizId().toString(),UserContext.getUser().toString());
        return ObjectUtils.isNotEmpty(result) && result > 0;
    }
    //新增点赞记录

    private Boolean addlike(LikeRecordFormDTO likeRecordFormDTO) {
        Long result =redisTemplate.opsForSet().add(likeRecordFormDTO.getBizId().toString(), UserContext.getUser().toString());
        return ObjectUtils.isNotEmpty(result) && result > 0;
    }
}
